package org.sang.controller;

import io.swagger.annotations.ApiOperation;
import org.sang.pojo.RespBean;
import org.sang.service.OssClientService;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/upload")
public class UploadFileController {

    @Resource
    private OssClientService ossClientService;

    @PostMapping("/user/avatar")
    @ApiOperation(value = "userAvatar", notes = "用户上传头像接口",
            produces = "application/octet-stream", consumes = "application/json")
    public RespBean<String> uploadUserAvatar(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        RespBean<String> respBean = new RespBean<>();
        assert file != null;
        String downloadUrl = ossClientService.uploadImageFile(file, "avatar");
        if (!StringUtils.isEmpty(downloadUrl)) {
            respBean.setStatus(200);
            respBean.setMsg("success");
            respBean.setData(downloadUrl);
        } else {
            respBean.setStatus(500);
            respBean.setMsg("upload file failed");
        }
        return respBean;
    }

    @PostMapping("/ckEditor/simpleUploadAdapter")
    public Map<String, String> uploadCkEditorImage(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("upload");// 获取上传文件对象
        assert file != null;
        String imageUrl = ossClientService.uploadImageFile(file, "simpleUploadAdapter");
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("url", imageUrl);
        return resultMap;
    }

}
